package com.xgc.book.bookserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgc.book.bookserver.bean.TokenBean;
import com.xgc.book.bookserver.mapper.TokenMapper;
import com.xgc.book.bookserver.service.TokenService;
import com.xgc.book.bookserver.util.ResultJson;
import com.xgc.book.bookserver.util.shiro.TokenGenerator;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * <p>
 * 登录状态表 服务实现类
 * </p>
 *
 * @author wrz
 * @since 2023-11-20
 */
@Service
@Transactional
public class TokenServiceImpl extends ServiceImpl<TokenMapper, TokenBean> implements TokenService {

    @Override
    public TokenBean getByToken(String token) {
        return this.getOne(new QueryWrapper<TokenBean>().eq("token", token));
    }

    @Override
    public TokenBean getByUserId(int userId) {
        return this.getOne(new QueryWrapper<TokenBean>().eq("user_id", userId));
    }

    @Override
    public ResultJson saveToken(int userId) {
        TokenBean tokenBean = this.getByUserId(userId);
        if (tokenBean == null) {
            tokenBean = new TokenBean();
        }
        tokenBean.setUserId(userId);
        tokenBean.setToken(TokenGenerator.generateValue());
        Date date = new Date();
        date.setHours(date.getHours() + 4);
        tokenBean.setExpires(date);
        this.saveOrUpdate(tokenBean);
        return ResultJson.ok(tokenBean.getToken());
    }
}
